/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Model.CreditCard;
import Model.CreditCardManager;
import Model.CustomerManager;
import Model.Product;
import Model.RandomGenerator;
import Model.Transaction;
import Model.UserManager;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author 013v
 */
public class CustomerPurchaseProducts extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            CreditCard cc = new CreditCard();
            cc.setCCCardNum(request.getParameter("cardNumber"));
            cc.setCCType(request.getParameter("cardType"));
            cc.setCCExpiry(request.getParameter("expiry"));

            Object tempaid = request.getSession().getAttribute("username");
            String aid = (String) tempaid;
            String uid = new UserManager().getAccountIDFromUser(aid);

            boolean cred = new CreditCardManager().isValidCard(cc, uid);
            if (cred == true) {
                Product newProd = new Product();
                Object cartObject = request.getSession().getAttribute("cartArray");
                String[][] userCart = (String[][]) cartObject;
                int tempStock = 0;
                int max = userCart[0].length;
                boolean res = false;
                for(int n=0; n<max; n++){
                    if (userCart[0][n] != null) {
                        newProd.setProductID(Integer.parseInt(userCart[0][n]));
                        newProd.setProductQuantity(new CustomerManager().getStock(Integer.toString(newProd.getProductID())));
                        tempStock = newProd.getProductQuantity() - Integer.parseInt(userCart[1][n]);
                        if(tempStock >= 0){
                            res = new CustomerManager().decreaseStock(newProd, userCart[1][n]);   
                        }
                    }

                }


                    if (res == true) {
                        //transaction phase start
                        Transaction newTrans = new Transaction();
                        int newID = new RandomGenerator().generateTransactionID();

                        newTrans.setTransactionID(newID);

                        int total = 0;
                        int index = userCart[0].length;
                        for (int i = 0; i < index; i++) {
                            if (userCart[0][i] != null) {
                                total = total + Integer.parseInt(userCart[2][i]);
                            }
                        }

                        newTrans.setTransactionTotal(total);

                        newTrans.setAccountID(uid);

                        boolean result = new CustomerManager().ProductCheckOut(newTrans, userCart);

                        if (result == true) {
                            for (int j = 0; j < index; j++) {
                                userCart[0][j] = null;
                                userCart[1][j] = null;
                                userCart[2][j] = null;
                            }
                            request.getSession().setAttribute("numCart", "0");
                            response.sendRedirect("receipt.jsp");
                        } else {
                            response.sendRedirect("checkOut.jsp?mess=purcherr"); //unable to process purchase
                        }

                    }
                    else{
                        response.sendRedirect("checkOut.jsp?mess=stockuperr"); //error in updating stocks
                    }
                }  else {
                response.sendRedirect("checkOut.jsp?mess=carderr"); //card is invalid
            }

//delivery address not yet working
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
